export default class ViewService {
    static #instance = null;
    #handlers = new Map();

    constructor(){
        if (ViewService.#instance) {
            return ViewService.#instance;
        }
        ViewService.#instance = this;
    }

     // 事件回调注册
    register(view, handlers = {}){
        if (typeof view === 'string'){
            view = view.trim();
            if (view && typeof handlers === 'object'){
                if (Object.getPrototypeOf(handlers) !== null){
                    handlers = Object.assign(Object.create(null), handlers);
                }
                this.remove(view);
                this.#handlers.set(view, handlers);
                return true;
            }
        }
        return false;
    }

    // 检查是否已注册
    has(view){
        if (typeof view === 'string'){
            view = view.trim();
            return view && this.#handlers.has(view);
        }
        return false;
    }

    // 获取指定组件或事件的回调
    get(view, event = null){
        if (typeof view !== 'string'){throw new Error('The view name must be of string type.')}
        view = view.trim();
        if (view && this.has(view)){
            const handlers = this.#handlers.get(view);
            if (typeof handlers === 'object'){
                if (typeof event === 'string'){
                    event = event.trim();
                    if (event && Object.hasOwn(handlers, event)){return handlers[event];}
                } else {
                    return handlers;
                }
            }
        }
        return null;
    }

    // 组件卸载后手动销毁回调
    remove(view){
        if (typeof view === 'string'){
            view = view.trim();
            if (view && this.has(view)){
                this.#handlers.delete(view);
                return true;
            }
        }
        return false;
    }

    clear() {this.#handlers.clear();return true;}
}
